package com.ruoyi.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Flow.Publisher;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

@Controller
@RequestMapping("/wechat")
public class WechatController {
	
    @Autowired
    private ISysUserService userService;
    
	@Autowired
	private ISysDeptService sysDeptService;
	
	@Autowired
	private ISysUserService sysUserService;
    
	private CorpWechatAppHelper clockApp = new CorpWechatAppHelper("wwf318d2b0fcd81545", "sCAhoTknhMLjxp7AmCQJo9wrbpUOWpYvTQfVUnOa0XA");
	private CorpWechatContactHelper contactApp = new CorpWechatContactHelper("wwf318d2b0fcd81545", "MvZSyDHwDfcrHaGLp5ybAgQ5OWBZMc_GYsuslD5aZ8M");

	private String prefix = "system/wechat";
	
	// -----------------------------------------------------------------------------------------------------------------------------
	
    private void syncDept() {
    	JSONArray array = contactApp.getAllDepartment();
    	for(int i = 0; i < array.size(); i++) {
    		JSONObject json = array.getJSONObject(i);
    		
    		SysDept dept = new SysDept();
    		dept.setDeptId(json.getLong("id"));
    		dept.setParentId(json.getLong("parentid"));
    		dept.setDeptName(json.getString("name"));
    		dept.setOrderNum(json.getInteger("order") + "");
    		dept.setStatus("0");
    		
    		SysDept oldDept = sysDeptService.selectDeptById(dept.getDeptId());
    		if(oldDept != null) {
    			oldDept.setDeptName(dept.getDeptName());
    			oldDept.setOrderNum(dept.getOrderNum());
    			oldDept.setParentId(dept.getParentId());
    			sysDeptService.updateDept(dept);
    		}else {
    			sysDeptService.insertDept(dept);	
    		}
    	}
    }
    
    private void syncPerson(int deptId) {
    	JSONArray array = contactApp.getDeptAllPerson(deptId);
    	for(int i = 0; i < array.size(); i++) {
    		JSONObject json = array.getJSONObject(i);
    		
    		SysUser user = new SysUser();
    		user.setLoginName(json.getString("userid"));
    		user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(encryptPassword(user.getLoginName(), "123456", user.getSalt()));
    		user.setUserName(json.getString("name"));
    		user.setUserType(UserConstants.REGISTER_USER_TYPE);
    		user.setStatus("0");
    		user.setDelFlag("0");
    		user.setDeptId(1l);
    		user.setDeptId2(1l);
    		JSONArray depts = json.getJSONArray("department");
    		for(int j = 0; j < depts.size(); j++) {
    			if(user.getDeptId() != null) {
    				user.setDeptId(depts.getLong(j));
    			}else if(user.getDeptId2() != null) {
    				user.setDeptId2(depts.getLong(j));
    			}
    		}
    		
    		SysUser oldUser = sysUserService.selectUserByLoginName(user.getLoginName());
    		if(oldUser != null) {
    			oldUser.setDeptId(user.getDeptId());
    			oldUser.setDeptId2(user.getDeptId2());
    			sysUserService.updateUser(oldUser);
    		}else {
    			sysUserService.insertUser(user);
    		}
    	}
    }
    
    private void syncPerson(int deptId, Long... roleId) {
    	JSONArray array = contactApp.getDeptAllPerson(deptId);
    	for(int i = 0; i < array.size(); i++) {
    		JSONObject json = array.getJSONObject(i);
    		
    		SysUser user = new SysUser();
    		user.setLoginName(json.getString("userid"));
    		user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(encryptPassword(user.getLoginName(), "123456", user.getSalt()));
    		user.setUserName(json.getString("name"));
            // "00"=>系统用户，"01"=>注册用户
    		user.setUserType(UserConstants.REGISTER_USER_TYPE);
    		user.setStatus("0");
    		user.setDelFlag("0");
    		user.setDeptId(1l);
    		user.setDeptId2(1l);
    		user.setRoleIds(roleId);
    		JSONArray depts = json.getJSONArray("department");
    		for(int j = 0; j < depts.size(); j++) {
    			if(user.getLoginName().equals("wangXiaoPing")){
    				System.out.println("部门id: " + depts.getLong(j));
    			}
    			
    			if(j == 0) {
    				user.setDeptId(depts.getLong(j));
    			}else if(j == 1) {
    				user.setDeptId2(depts.getLong(j));
    			}
    		}
    		
    		SysUser oldUser = sysUserService.selectUserByLoginName(user.getLoginName());
    		if(oldUser != null) {
    			oldUser.setDeptId(user.getDeptId());
    			oldUser.setDeptId2(user.getDeptId2());
    			oldUser.setDelFlag("0");
    			sysUserService.updateUserInfo(oldUser);
    		}else {
    			sysUserService.insertUser(user);
    		}
    	}
    }
    
    public String encryptPassword(String loginName, String password, String salt)
    {
        return new Md5Hash(loginName + password + salt).toHex();
    }
    
	@GetMapping("sync_dept")
	@ResponseBody
    public synchronized String apiSyncDept()
    {	
		syncDept();
        return "ok";
    }
	
	@GetMapping("sync_user")
	@ResponseBody
    public synchronized String apiSyncUser()
    {
    	syncPerson(1, 100l);
        return "同步完成";
    }
	
	// -----------------------------------------------------------------------------------------------------------------------------
	 
    @GetMapping("my_clock")
    public String myclock(String code, ModelMap mmap)
    {
    	String loginName = clockApp.getUserId(code);
    	mmap.put("LOGINNAME", loginName);
    	
    	SysUser user = userService.selectUserByLoginName(loginName);
    	
    	if(user == null) {
    		return prefix + "/no_user_find";
    	}else {
    		mmap.put("USERID", user.getUserId());
    	}
    	
        return prefix + "/my_clock";
    }
	
    @GetMapping("persion_clock")
    public String clock(String code, ModelMap mmap)
    {
    	String loginName = clockApp.getUserId(code);
    	mmap.put("LOGINNAME", loginName);
    	
    	SysUser user = userService.selectUserByLoginName(loginName);
    	
    	if(user == null) {
    		return prefix + "/no_user_find";
    	}else {
    		mmap.put("USERID", user.getUserId());
    	}
    	
        return prefix + "/persion_clock";
    }
    
    @GetMapping("persions_clock")
    public String psclock(String code, String USERID, String LOGINNAME, ModelMap mmap)
    {
    	if(code == null && USERID != null) {
    		mmap.put("LOGINNAME", LOGINNAME);
    		mmap.put("USERID", USERID);
    		return prefix + "/persions_clock";
    	}
    	
    	String loginName = clockApp.getUserId(code);
    	mmap.put("LOGINNAME", loginName);
    	
    	SysUser user = userService.selectUserByLoginName(loginName);
    	
    	if(user == null) {
    		mmap.put("CODE", code);
    		
    		return prefix + "/no_user_find";
    	}else {
    		if(!hasRole("manag", user.getRoles()) && !hasRole("zuzhang", user.getRoles())) {
    			return prefix + "/no_per_has";
    		}
    		mmap.put("USERID", user.getUserId());
    	}
    	
        return prefix + "/persions_clock";
    }
    
    @GetMapping("persions_clock2")
    public String psclock2(String code, String USERID, String LOGINNAME, ModelMap mmap)
    { 
    	if(code == null && USERID != null) {
    		mmap.put("LOGINNAME", LOGINNAME);
    		mmap.put("USERID", USERID);
    		return prefix + "/persions_clock2";
    	}
    	
    	String loginName = clockApp.getUserId(code);
    	mmap.put("LOGINNAME", loginName);
    	
    	SysUser user = userService.selectUserByLoginName(loginName);
    	
    	if(user == null) {
    		mmap.put("CODE", code);
    		
    		return prefix + "/no_user_find";
    	}else {
    		if(!hasRole("manag", user.getRoles()) && !hasRole("zuzhang", user.getRoles())) {
    			return prefix + "/no_per_has";
    		}
    		mmap.put("USERID", user.getUserId());
    	}
    	
        return prefix + "/persions_clock2";
    }
    
    @GetMapping("devices_clock")
    public String declock(String code, ModelMap mmap)
    {
    	String loginName = clockApp.getUserId(code);
    	mmap.put("LOGINNAME", loginName);
    	
    	SysUser user = userService.selectUserByLoginName(loginName);
    	
    	if(user == null) {
    		mmap.put("CODE", code);
    		return prefix + "/no_user_find";
    	}else {
    		if(!hasRole("manag", user.getRoles()) && !hasRole("zuzhang", user.getRoles())) {
    			return prefix + "/no_per_has";
    		}
    		
    		mmap.put("USERID", user.getUserId());
    	}
    	
        return prefix + "/devices_clock";
    }
    
    private boolean hasRole(String roleKey, List<SysRole> roles) {
    	for(SysRole r : roles) {
    		if (r.getRoleKey().equals(roleKey)) {
				return true;
			}
    	}
    	return false;
    }
}
